import os
from PIL import Image, ImageDraw, ImageFont

WIDTH, HEIGHT = 1920, 1080
OUTPUT_DIR = os.path.join(os.path.dirname(__file__), 'static', 'pic')

# Try to load a Chinese-capable font on Windows; fallback to default
FONT_CANDIDATES = [
    r"C:\\Windows\\Fonts\\msyh.ttc",  # Microsoft YaHei
    r"C:\\Windows\\Fonts\\msyh.ttf",
    r"C:\\Windows\\Fonts\\simhei.ttf",
    r"C:\\Windows\\Fonts\\simsun.ttc",
]


def get_font(size: int) -> ImageFont.FreeTypeFont:
    for path in FONT_CANDIDATES:
        if os.path.exists(path):
            try:
                return ImageFont.truetype(path, size)
            except Exception:
                continue
    return ImageFont.load_default()


def save_jpg(img: Image.Image, filename: str):
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    path = os.path.join(OUTPUT_DIR, filename)
    img.save(path, format='JPEG', quality=95, subsampling=0, optimize=True)
    print(f"Saved: {path}")


def header(draw: ImageDraw.ImageDraw, title: str, bg=(30, 64, 175)):
    draw.rectangle([0, 0, WIDTH, 80], fill=bg)
    draw.text((40, 26), title, fill=(255, 255, 255), font=get_font(32))


def rounded_rect(draw, xy, radius, fill, outline=None, width=1):
    x0, y0, x1, y1 = xy
    draw.rounded_rectangle([x0, y0, x1, y1], radius=radius, fill=fill, outline=outline, width=width)


def draw_kpi_card(draw, rect, title, value, colors):
    x0, y0, x1, y1 = rect
    rounded_rect(draw, rect, 18, fill=colors[0], outline=colors[1])
    draw.text((x0 + 20, y0 + 26), title, fill=colors[2], font=get_font(28))
    draw.text((x0 + 20, y0 + 72), value, fill=colors[3], font=get_font(48))


def img_base(title: str, bg=(248, 250, 252)):
    img = Image.new('RGB', (WIDTH, HEIGHT), bg)
    draw = ImageDraw.Draw(img)
    header(draw, title)
    rounded_rect(draw, (60, 120, 1860, 1020), 16, fill=(255, 255, 255), outline=(229, 231, 235))
    return img, draw


def img_1_1():
    img, draw = img_base('AI每节一练 - 智能命题系统', (248, 250, 252))
    # 左侧输入
    rounded_rect(draw, (100, 160, 900, 980), 12, fill=(249, 250, 251), outline=(209, 213, 219))
    draw.text((120, 190), '知识点输入', fill=(55, 65, 81), font=get_font(26))
    rounded_rect(draw, (120, 230, 880, 430), 10, fill=(255, 255, 255), outline=(209, 213, 219))
    tips = [
        '请输入本节课的核心知识点：',
        '• Python中的条件语句if-elif-else',
        '• 逻辑运算符的使用',
        '• 嵌套条件语句的应用',
    ]
    y = 260
    for t in tips:
        draw.text((140, y), t, fill=(55, 65, 81), font=get_font(22))
        y += 34
    draw.text((120, 480), '难度设置', fill=(55, 65, 81), font=get_font(24))
    draw.ellipse((150-8, 510-8, 150+8, 510+8), fill=(59, 130, 246))
    draw.text((170, 498), '基础 (30%)', fill=(55, 65, 81), font=get_font(20))
    draw.ellipse((280-8, 510-8, 280+8, 510+8), fill=(59, 130, 246))
    draw.text((300, 498), '中等 (50%)', fill=(55, 65, 81), font=get_font(20))
    draw.ellipse((410-8, 510-8, 410+8, 510+8), outline=(209, 213, 219), width=2, fill=(107,114,128))
    draw.text((430, 498), '困难 (20%)', fill=(55, 65, 81), font=get_font(20))
    # 生成按钮
    rounded_rect(draw, (120, 620, 320, 670), 10, fill=(59, 130, 246))
    draw.text((140, 632), '🤖 AI智能生成', fill=(255, 255, 255), font=get_font(22))

    # 右侧预览
    rounded_rect(draw, (940, 160, 1820, 980), 12, fill=(249, 250, 251), outline=(209, 213, 219))
    draw.text((960, 190), '生成预览', fill=(55, 65, 81), font=get_font(26))
    rounded_rect(draw, (960, 230, 1800, 350), 10, fill=(255, 255, 255), outline=(229, 231, 235))
    draw.text((980, 260), '题目1：以下Python代码的输出结果是？', fill=(31, 41, 55), font=get_font(24))
    code = ['x = 10', 'if x > 5 and x < 15:', '    print("条件成立")']
    y = 295
    for line in code:
        draw.text((980, y), line, fill=(31, 41, 55), font=get_font(22))
        y += 30

    rounded_rect(draw, (960, 370, 1800, 470), 10, fill=(255, 255, 255), outline=(229, 231, 235))
    draw.text((980, 395), '题目2：下列关于elif语句的说法正确的是？', fill=(31, 41, 55), font=get_font(24))
    draw.text((980, 430), 'A. elif可以单独使用    B. elif必须配合if使用', fill=(31, 41, 55), font=get_font(20))

    # 状态
    rounded_rect(draw, (960, 880, 1800, 940), 10, fill=(236, 253, 245), outline=(16, 185, 129))
    draw.text((980, 898), '✅ AI分析完成 · 已生成8道题目，覆盖所有知识点，难度分布合理', fill=(5, 150, 105), font=get_font(20))

    save_jpg(img, '1.1_AI智能命题界面.jpg')


def draw_bar(draw, x, base_y, w, h, color):
    draw.rectangle([x, base_y - h, x + w, base_y], fill=color)


def img_1_2():
    img, draw = img_base('教师后台 · 班级教学看板', (247, 250, 252))
    # 左侧导航
    rounded_rect(draw, (60+20, 140, 60+20+280, 1020-20), 12, fill=(14, 165, 233, 15), outline=(219, 234, 254))
    draw.text((100, 180), '功能导航', fill=(15, 23, 42), font=get_font(24))
    for i, t in enumerate(['• 班级管理', '• 作业/练习', '• 学情分析', '• 题库管理']):
        draw.text((100, 220 + i*34), t, fill=(51, 65, 85), font=get_font(20))

    # 顶部操作条
    rounded_rect(draw, (360, 160, 1850, 220), 10, fill=(241, 245, 249), outline=(226, 232, 240))
    draw.text((380, 186), '当前班级：高一(2)班', fill=(15, 23, 42), font=get_font(22))
    rounded_rect(draw, (1700, 170, 1840, 210), 8, fill=(59, 130, 246))
    draw.text((1716, 178), '发布练习', fill=(255, 255, 255), font=get_font(20))

    # KPI
    draw_kpi_card(draw, (360, 240, 820, 400), '今日练习参与', '96%', ((236, 254, 255), (186, 230, 253), (3, 105, 161), (14, 165, 233)))
    draw_kpi_card(draw, (840, 240, 1300, 400), '平均正确率', '82%', ((240, 253, 244), (187, 247, 208), (22, 101, 52), (22, 163, 74)))
    draw_kpi_card(draw, (1320, 240, 1850, 400), '需关注学生', '5', ((255, 247, 237), (254, 215, 170), (154, 52, 18), (234, 88, 12)))

    # 柱状图
    rounded_rect(draw, (360, 420, 1850, 790), 12, fill=(248, 250, 252), outline=(226, 232, 240))
    draw.text((380, 450), '成绩分布 (本次练习)', fill=(15, 23, 42), font=get_font(22))
    base = 770
    x = 420
    heights = [120,150,210,250,270,230,170,110]
    for h in heights:
        draw_bar(draw, x, base, 60, h, (96, 165, 250))
        x += 100

    # 待处理
    rounded_rect(draw, (360, 820, 1850, 1000), 12, fill=(255,255,255), outline=(226,232,240))
    draw.text((380, 855), '待处理事项', fill=(15, 23, 42), font=get_font(22))
    draw.text((380, 895), '• 发布下一次课后“每节一练”', fill=(51, 65, 85), font=get_font(20))
    draw.text((900, 895), '• 关注5名学生的错题巩固', fill=(51, 65, 85), font=get_font(20))

    save_jpg(img, '1.2_教师后台操作场景.jpg')


def img_2_1():
    img, draw = img_base('学生端 · 在线答题', (248, 250, 252))
    draw.text((100, 190), '单选题 1/10', fill=(15, 23, 42), font=get_font(24))
    draw.text((100, 230), '以下Python代码的输出结果是？', fill=(51, 65, 85), font=get_font(22))
    rounded_rect(draw, (100, 250, 1820, 390), 10, fill=(241, 245, 249), outline=(226, 232, 240))
    draw.text((120, 285), 'x = 7', fill=(17,24,39), font=get_font(22))
    draw.text((120, 315), 'if x % 2 == 1: print("odd")', fill=(17,24,39), font=get_font(22))

    def option(y, text, active=False):
        rounded_rect(draw, (100, y, 1820, y+70), 10, fill=(255,255,255), outline=(219, 234, 254) if active else (229,231,235))
        color = (59,130,246) if active else (229,231,235)
        draw.ellipse((130-10, y+35-10, 130+10, y+35+10), fill=color)
        draw.text((160, y+30), text, fill=(15,23,42), font=get_font(20))
    option(420, 'A. odd', True)
    option(510, 'B. even')
    option(600, 'C. 报错')
    option(690, 'D. 无输出')

    rounded_rect(draw, (100, 810, 300, 864), 10, fill=(59,130,246))
    draw.text((160, 828), '提交', fill=(255,255,255), font=get_font(22))
    draw.text((1500, 828), '剩余时间：09:45', fill=(51,65,85), font=get_font(20))

    save_jpg(img, '2.1_学生在线答题界面.jpg')


def img_2_2():
    img, draw = img_base('成绩报告', (249, 250, 251))
    draw.text((120, 190), '正确率', fill=(15,23,42), font=get_font(24))
    # donut
    cx, cy, r = 260, 400, 140
    draw.ellipse((cx-r, cy-r, cx+r, cy+r), fill=(226,232,240))
    # 82% arc (approximate)
    draw.pieslice((cx-r, cy-r, cx+r, cy+r), start=-90, end=-90+295, fill=(52, 211, 153))
    draw.ellipse((cx-90, cy-90, cx+90, cy+90), fill=(255,255,255))
    draw.text((cx-30, cy-20), '82%', fill=(6,95,70), font=get_font(36))

    draw.text((560, 190), '各知识点正答率', fill=(15,23,42), font=get_font(24))
    rounded_rect(draw, (560, 220, 1800, 570), 10, fill=(248,250,252), outline=(226,232,240))
    base = 560
    x = 600
    for h in [100,140,180,220,200,160,120]:
        draw_bar(draw, x, base, 70, h, (96,165,250))
        x += 120

    draw.text((120, 620), '能力维度', fill=(15,23,42), font=get_font(24))
    rounded_rect(draw, (120, 650, 1800, 980), 10, fill=(248,250,252), outline=(226,232,240))
    for i, t in enumerate(['理解','应用','分析','评价']):
        draw.text((140+i*100, 690), t, fill=(51,65,85), font=get_font(20))

    save_jpg(img, '2.2_可视化成绩报告.jpg')


def img_2_3():
    img, draw = img_base('错题解析', (248, 250, 252))
    draw.text((100, 190), '题目', fill=(15,23,42), font=get_font(24))
    rounded_rect(draw, (100, 210, 1820, 340), 10, fill=(241, 245, 249), outline=(226, 232, 240))
    draw.text((120, 250), '以下代码运行后变量y的值为多少？', fill=(17,24,39), font=get_font(22))

    rounded_rect(draw, (100, 360, 1820, 420), 10, fill=(236,253,245), outline=(16,185,129))
    draw.text((120, 375), '正确答案：B. 42', fill=(6,95,70), font=get_font(22))

    rounded_rect(draw, (100, 440, 1820, 500), 10, fill=(254,242,242), outline=(254,202,202))
    draw.text((120, 455), '你的选择：A. 40', fill=(185,28,28), font=get_font(22))

    draw.text((100, 540), '解析', fill=(15,23,42), font=get_font(24))
    rounded_rect(draw, (100, 560, 1820, 980), 10, fill=(249,250,251), outline=(229,231,235))
    for i, t in enumerate(['1. 题目考查变量赋值与运算顺序','2. 正确计算路径为：先乘法→再加法→最后赋值','3. 可通过举例验证结果']):
        draw.text((120, 600+i*40), t, fill=(51,65,85), font=get_font(22))

    save_jpg(img, '2.3_错题解析详情.jpg')


def img_3_1():
    img, draw = img_base('班级学情数据看板', (248, 250, 252))
    draw_kpi_card(draw, (100, 160, 500, 300), '参与率', '96%', ((236,254,255),(186,230,253),(3,105,161),(14,165,233)))
    draw_kpi_card(draw, (540, 160, 940, 300), '平均分', '82', ((240,253,244),(187,247,208),(22,101,52),(22,163,74)))
    draw_kpi_card(draw, (980, 160, 1380, 300), '优秀率', '28%', ((255,247,237),(254,215,170),(154,52,18),(234,88,12)))
    draw_kpi_card(draw, (1420, 160, 1820, 300), '需帮扶', '5人', ((254,242,242),(254,202,202),(153,27,27),(220,38,38)))

    draw.text((100, 340), '近七次练习得分趋势', fill=(15,23,42), font=get_font(22))
    rounded_rect(draw, (100, 360, 1780, 660), 12, fill=(248,250,252), outline=(226,232,240))
    pts = [(120,620),(360,560),(600,540),(840,520),(1080,500),(1320,520),(1560,480),(1760,490)]
    draw.line(pts, fill=(59,130,246), width=6, joint='curve')
    for x,y in pts:
        draw.ellipse((x-6,y-6,x+6,y+6), fill=(59,130,246))

    draw.text((100, 700), '题型正确率', fill=(15,23,42), font=get_font(22))
    rounded_rect(draw, (100, 720, 920, 1000), 12, fill=(248,250,252), outline=(226,232,240))
    cx, cy, r = 310, 860, 110
    draw.ellipse((cx-r,cy-r,cx+r,cy+r), fill=(226,232,240))
    draw.pieslice((cx-r,cy-r,cx+r,cy+r), start=-90, end=230, fill=(16,185,129))
    draw.ellipse((cx-70,cy-70,cx+70,cy+70), fill=(255,255,255))
    draw.text((220, 865), '选择 87%', fill=(6,95,70), font=get_font(24))

    draw.text((960, 700), '班级排名 (Top 5)', fill=(15,23,42), font=get_font(22))
    rounded_rect(draw, (960, 720, 1780, 1000), 12, fill=(248,250,252), outline=(226,232,240))
    for i, row in enumerate(['1. 张三 96','2. 李四 94','3. 王五 92','4. 赵六 90','5. 周七 89']):
        draw.text((980, 760+i*40), row, fill=(51,65,85), font=get_font(22))

    save_jpg(img, '3.1_班级学情数据看板.jpg')


def img_3_2():
    img, draw = img_base('共性错题统计分析', (248, 250, 252))
    draw.text((100, 180), 'Top 6 错题 (错误率)', fill=(15,23,42), font=get_font(24))
    rounded_rect(draw, (100, 200, 1820, 940), 12, fill=(248,250,252), outline=(226,232,240))
    items = [
        ('题目1：逻辑运算优先级', 0.72, (252,165,165), (153,27,27)),
        ('题目2：循环边界条件', 0.65, (253,186,116), (154,52,18)),
        ('题目3：列表切片',     0.60, (252,211,77),  (146,64,14)),
        ('题目4：字典访问',     0.54, (167,243,208), (6,95,70)),
        ('题目5：函数参数',     0.49, (147,197,253), (30,64,175)),
        ('题目6：文件读写',     0.41, (199,210,254), (55,48,163)),
    ]
    y = 240
    for name, rate, bar, txt in items:
        draw.text((120, y), name, fill=(51,65,85), font=get_font(22))
        full = 1200
        w = int(full * rate)
        rounded_rect(draw, (400, y-20, 400+w, y+6), 6, fill=bar)
        draw.text((1220, y), f"错误率 {int(rate*100)}%", fill=txt, font=get_font(20))
        y += 80

    save_jpg(img, '3.2_共性错题统计分析.jpg')


def img_3_3():
    img = Image.new('RGB', (WIDTH, HEIGHT))
    draw = ImageDraw.Draw(img)
    # gradient bg
    draw.rectangle([0,0,WIDTH,HEIGHT], fill=(224,242,254))
    rounded_rect(draw, (100, 120, 1820, 960), 18, fill=(255,255,255), outline=(219,234,254))
    rounded_rect(draw, (140, 160, 1040, 680), 12, fill=(11,31,67))
    draw.text((160, 190), '数据投屏 · 正答率趋势', fill=(147,197,253), font=get_font(22))
    pts = [(180,620),(260,560),(340,540),(420,520),(500,500),(580,520),(660,480),(740,490)]
    draw.line(pts, fill=(96,165,250), width=6)
    for x,y in pts:
        draw.ellipse((x-6,y-6,x+6,y+6), fill=(96,165,250))
    # silhouettes
    draw.polygon([(1250,500),(1410,500),(1410,700),(1250,700)], fill=(15,23,42))
    draw.ellipse((1310-40,460-40,1310+40,460+40), fill=(15,23,42))
    draw.ellipse((1500-40,730-40,1500+40,730+40), fill=(15,23,42))
    draw.rounded_rectangle((1460,770,1540,890), 20, fill=(15,23,42))
    draw.ellipse((1580-36,750-36,1580+36,750+36), fill=(15,23,42))
    draw.rounded_rectangle((1548,786,1612,890), 18, fill=(15,23,42))

    rounded_rect(draw, (100, 700, 1820, 920), 12, fill=(248,250,252), outline=(226,232,240))
    draw.text((120, 740), '基于学情数据的靶向讲解', fill=(15,23,42), font=get_font(24))
    draw.text((120, 780), '• 根据共性错题，重点讲解易错知识点；根据个体差异，分层推进', fill=(51,65,85), font=get_font(22))
    draw.text((120, 820), '• 课堂内快速检验掌握度，形成“教学-测评-分析-调教”闭环', fill=(51,65,85), font=get_font(22))

    save_jpg(img, '3.3_教师利用数据教学场景.jpg')


def img_3_4():
    img = Image.new('RGB', (WIDTH, HEIGHT), (31,41,55))
    draw = ImageDraw.Draw(img)
    # simple sunset-like top
    draw.rectangle([0,0,WIDTH,840], fill=(252,211,77))
    draw.rectangle([0,840,WIDTH,1080], fill=(31,41,55))

    # silhouettes teacher + students
    draw.ellipse((320-48,720-48,320+48,720+48), fill=(17,24,39))
    draw.rounded_rectangle((280,760,360,920), 20, fill=(17,24,39))
    draw.arc((340,740,460,820), start=200, end=340, width=20, fill=(17,24,39))

    for base_x in [720, 980, 1240]:
        draw.ellipse((base_x-40,760-40,base_x+40,760+40), fill=(17,24,39))
        draw.rounded_rectangle((base_x-30,800,base_x+30,940), 18, fill=(17,24,39))
        draw.rounded_rectangle((base_x+40,740,base_x+60,920), 10, fill=(17,24,39))

    draw.text((WIDTH//2-180, 160), '课堂互动 · 积极举手', fill=(31,41,55), font=get_font(40))

    save_jpg(img, '3.4_师生课堂互动照片.jpg')


def main():
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    img_1_1()
    img_1_2()
    img_2_1()
    img_2_2()
    img_2_3()
    img_3_1()
    img_3_2()
    img_3_3()
    img_3_4()
    print('All JPG images generated in static/pic')


if __name__ == '__main__':
    main()